#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Inet_Addr.hpp"
#include "Com_ERR.hpp"

namespace SocketModule
{
    using namespace LogModule;

    const static int g_blcklog = 8; // 全连接队列的长度

    class Socket; // 前置声明
    using SockSPtr = std::shared_ptr<Socket>;

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void CreateBindOrDie(uint16_t port) = 0;
        virtual void CreateListenOrDie(int blcklog = g_blcklog) = 0;
        virtual SockSPtr Accepter(Inet_Addr *clientaddr) = 0;
        virtual bool Connector(const std::string &server_ip, uint16_t server_port) = 0;

        virtual int Sockfd() = 0;
        virtual void Close() = 0;

        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocketOrDie();
            CreateBindOrDie(port);
            CreateListenOrDie();
        }

        bool BuildClientSoket(const std::string &server_ip, uint16_t server_port)
        {
            CreateSocketOrDie();
            return Connector(server_ip, server_port);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd = -1) : _sockfd(sockfd)
        {
        }

        void CreateSocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0); // 创建监听套接字
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create error\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket create success, sockfd: %d\n", _sockfd); // 3
        }

        void CreateBindOrDie(uint16_t port) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;         // 网络通信
            server.sin_port = htons(port);       // 主机端口的序列转为网络序列
            server.sin_addr.s_addr = INADDR_ANY; // 服务端绑定任意的 ip

            if (::bind(_sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "bind success, sockfd is %d\n", _sockfd);
        }

        void CreateListenOrDie(int blcklog) override
        {
            if (::listen(_sockfd, blcklog) < 0)
            {
                LOG(FATAL, "listen error\n");
            }
            LOG(INFO, "listen success\n");
        }

        SockSPtr Accepter(Inet_Addr *clientaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(FATAL, "accept error");
                return nullptr;
            }
            *clientaddr = Inet_Addr(client); // 将客户端的地址带出去，方便打印
            LOG(FATAL, "get a new link, client info: %s sockfd is %d\n", clientaddr->AddrStr().c_str(),sockfd);
            return std::make_shared<TcpSocket>(sockfd); // C++14
        }

        bool Connector(const std::string &server_ip, uint16_t server_port) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;                             // 网络通信
            server.sin_port = htons(server_port);                    // 主机端口的序列转为网络序列
            inet_pton(AF_INET, server_ip.c_str(), &server.sin_addr); // 将端口号设置为网络序列

            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            return true;
        }

        int Sockfd() override
        {
            return _sockfd;
        }

        void Close() override
        {
            if (_sockfd > 0)
                ::close(_sockfd);
        }

        ssize_t Recv(std::string *out) override
        {
            char buffer[4096];
            ssize_t n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            int n = ::send(_sockfd, in.c_str(), in.size(), 0);
            return n;
        }

    private:
        int _sockfd; // 可以是 监听套接字，也可以是 io 套接字
    };
}
